import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'

const downloadUrl = res => {
  const blob = new Blob([res.data], { type: res.data.type })
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  if (res.headers['content-disposition'] != null) {
    downloadElement.download = decodeURI(res.headers['content-disposition'].replace('attachment;filename=', ''))
  } else {
    downloadElement.download = "模板文件.xlsx"
  }
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  window.URL.revokeObjectURL(href)
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    //config是个大对象，里面有很多自带的默认属性。
    //这个config大对象是默认传递的，axios自带的，
    //{url: "/mock/home", params: {…}, headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …},其中： headers: {Accept: "application/json, text/plain, */*"}
    config.headers.Token = localStorage.getItem('Token') || ''; //设置请求头，给请求头对象添加token属性(localStorage.getItem("key"))
    return config;
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.constructor.name === 'Blob') {
      downloadUrl(response)
      return
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 'SYS000000102') {
        // to re-login
        MessageBox.confirm('登陆信息已经过期，请重新登陆', '', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return
      }
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
